package com.subalien.client.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.util.SC;
import com.subalien.client.MainTool;
import com.subalien.client.dto.LoginInfoDto;
import com.subalien.client.service.LoginServiceAsync;
import com.subalien.client.util.ServiceSingleton;

public class LoginTool {
	private LoginInfoDto loginInfoDto = null;

	public LoginTool() {
	}

	public void init() {
		System.out.println("LoginTool: init");
		LoginServiceAsync loginService = ServiceSingleton.getLoginServiceAsyncInstance();

		// XXX for hosted mode use this
		//loginService.login(GWT.getHostPageBaseURL() + "Subalien.html?gwt.codesvr=127.0.0.1:9997", new AsyncCallback<LoginInfoDto>() {
			// XXX for web mode use this
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfoDto>() {

			public void onSuccess(LoginInfoDto result) {
				loginInfoDto = result;
				if (result.isLoggedIn()) {
					MainTool.startGame();
				} else {
					redirect(loginInfoDto.getLoginUrl());
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	public void logout() {
		System.out.println("logout");
		redirect(loginInfoDto.getLogoutUrl());
		
		SC.showPrompt("Logging out");
		Timer t = new Timer() {
			public void run() {
				MainTool.init();
			}
		};

		t.schedule(5000);
	}

	public native void redirect(String url)/*-{
		$wnd.location.replace(url);
	}-*/;

	public LoginInfoDto getLoginInfoDto() {
		return loginInfoDto;
	}
}
